﻿using MediatR;
using RedDragon.Common.Domain.Manufacture;
using RedDragon.Common.Domain.Process;
using RedDragon.Common.Dtos;
using RedDragon.ERP.ErroCodeEnum;
using SqlSugar;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Proccess
{
    /// <summary>
    /// 根据工序Id获取工作中心
    /// </summary>
    public class SearchWorkCentersHandler : IRequestHandler<SearchWorkCentersCommon, Result>
    {
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 日志
        /// </summary>
        public readonly ILogger<SearchWorkCentersHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="logger"></param>
        public SearchWorkCentersHandler(ISqlSugarClient db, ILogger<SearchWorkCentersHandler> logger)
        {
            _db = db;
            _logger = logger;
        }

        /// <summary>
        /// 根据工序Id获取工作中心
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(SearchWorkCentersCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var query = _db.Queryable<Process, WorkCenters>((p, w) => p.WorkCentreCode == w.WorkCenterCode)
                    .Select((p, w) => new ProcessWorkCentersDto()
                    {
                        ProcessId = p.ProcessId,
                        WorkCenterName = w.WorkCenterName,
                    });
                //工序ID是否等于0
                if (request.ProcessId != 0)
                {
                    query = query.Where(p => p.ProcessId == request.ProcessId);
                }
                var list = await query.FirstAsync();
                if (list != null)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = list;
                    result.Msg = "根据工序Id获取工作中心成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "根据工序Id获取工作中心异常" + ex.Message;
                _logger.LogError("根据工序Id获取工作中心异常" + ex.Message);
            }
            return result;
        }

    }
}
